// pages/bookIntro/comment/index.js
Component({
  /**
   * 组件的属性列表
   */

  lifetimes: {
    attached() {
      this.getDataTime()
      // 获取gender初始数据
    },
    // 在组件实例进入页面节点树时执行
    detached() {
      // 在组件实例被从页面节点树移除时执行
    }
  },
  properties: {
    ids: {
      type: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    comment: [],
    flog: 0, // 用来标记页码。
    pageHidden: false, // 用来给页码元素做影藏
    tap: 20, // 表示每次显示的数据的数量

    lists: {
      content: [
        "默认排序",
        "最新发布",
        "权重最高",
        "最多评论"
      ],
      eng: ["updated", "created", "helpful", "comment-count"],
      color: [
        "aqua", "", "", ""
      ]
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getDataTime() {
      if (this.data.ids) {
        this.updata()
      } else {
        setTimeout(() => {
          this.getDataTime()
        }, 300) // 注意这里的this指向会影响this.data.ids/
      }
    },


    updata(flog = 0, toggle = "updated") {
      let that = this;
      this.setData({
        comment: ""
      })
      wx.request({
        url: `https://api.zhuishushenqi.com/post/review/by-book?book=${this.data.ids}&sort=${toggle}&start=${flog}&limit=20`,
        success: function(res) {
          res.data.reviews.forEach(val => {
            if (val.author.gender === "male") {
              val.author.gender = "男"
            }
            let getData = val.updated;
            let num = getData.indexOf("T");
            val.updated = getData.slice(0, num)

            let created = val.created;

            let num2 = created.indexOf("T");
            val.created = created.slice(0, num2)
          })

          if (res.data.total > flog + that.data.tap) {
            that.setData({
              pageHidden: true
            })
          } else {
            that.setData({
              pageHidden: false
            })
          }
          that.setData({
            comment: res.data.reviews
          })
        }
      })
    },



    nextPage() { // 翻下一页
      let flog = ++this.data.flog;
      let tap = this.data.tap;
      flog = flog * tap;
      this.updata(flog)
    },

    toggleData(e) {
      this.setData({
        flog: 0
      });
      let num = parseInt(e.target.id);
      let lists = this.data.lists;
      lists.color = lists.color.map((val, index) => {
        if (index === num) {
          val = "aqua"
        } else {
          val = ""
        }

        return val
      })

      this.setData({
        lists
      })

      let toggle = lists.eng[num]
      this.updata(0, toggle)
    },
  }
})